### Jonathan D. Klingler, Gary E. Hollibaugh, Jr., and Adam J. Ramey
### "Don't Know What You Got: A Bayesian Hierarchical Model of Neuroticism and Ideological Uncertainty
### Political Science Research and Methods
###
###
### Stylized Model of Opinion Formation (Figure 1)


library(ggplot2)
library(grDevices)

# neuroplot is a function to create a plot
neuroplot <- function(R, L, p, w, xmin, xmax, ymin, ymax, c, range1_x, range1_y, range2_x, range2_y, range3_x, range3_y){
		x <- seq(xmin, xmax, length.out = 500)
		y <- seq(ymin, ymax, length.out = 500)
		m <- R/L
		x_y_table <- expand.grid(data.frame(x,y))
		if(sum((c < w*(R*x_y_table$y + L*x_y_table$x)) == 0) > 0){print("c too high over range")} 
		else{x_y_table$region1 <- as.numeric(x_y_table$x < ((p/(1-p))*m*x_y_table$y))
			 x_y_table$region2 <- as.numeric(x_y_table$x >= ((p/(1-p))*m*x_y_table$y) & 
				 	 		 				 x_y_table$x < (((p + w)/(1 - p - w))*m*x_y_table$y - (c)*(L*(1-p-w))))
			 x_y_table$range <- 2*x_y_table$region1 + 1*x_y_table$region2
			 ggplot(x_y_table, aes(x = x, y = y, z = range)) + 
			    stat_contour(colour = "black") + 
			    scale_fill_grey(guide=FALSE, start = 0.2, end = 1) +
			    scale_x_continuous(expand = c(0,0), limits = c(xmin, xmax), breaks = c(1,4,7,10)) +
			    scale_y_continuous(expand = c(0,0), limits = c(ymin, ymax), breaks = c(1,4,7,10)) +
			    theme_bw() + 
				geom_tile(aes(fill = factor(range)), alpha = I(0.3)) + 
			    xlab('\nSensitivity to Negative Outcomes') +
			    ylab('Sensitivity to Reward') + 
			    theme(legend.position="none") + 
			    annotate("text", x = range1_x, y = range1_y, label = "Opinion Formation\nAlways") + 
			    annotate("text", x = range2_x, y = range2_y, label = "Opinion Formation\nIf Information Cost Paid") + 
			    annotate("text", x = range3_x, y = range3_y, label = "Opinion Formation\nNever") 
			    }}

# neuroplot-object is a plot (a ggplot object) created by the neuroplot() function at the specified parameters
neuroplot.object <- neuroplot(3,3,0.5,0.2,1,10,1,10,1, 3.5, 7, 7.25, 5, 7.5, 2) 


# save the neuro-plot object as a ps file			    
cairo_ps("neuro-model-example.eps", height=6, width=6)	
neuroplot.object
dev.off()